using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.FormsManagement;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// Summary description for ContinuingReviewSelectionPage.
    /// </summary>
    public partial class ContinuingReviewSelectionPage : BasePage
    {
        #region instance fields

        private ICachePolicy cachePolicy;
        private string crStudyType;
        private Hashtable pageCache;
        private ICachePolicy pageCachePolicy;
        private string processType;
        private Protocol protocol;
        private int protocolId;
        private QuestionnaireAnswer questionnaireAnswer;
        private int userAccessLevel;

        #endregion

        #region Constants

        private const string AnnunciatorTitle = "The following error(s) occurred...";
        private const string PageCacheKey = "CRSelectionPage_7487F998-7386-4edd-B012-004A28643924";
        private const string ProcessTypeKey = "processType_E4E00FC9-2A81-43fc-9EAE-ECB01B03B567";
        private const string ProtocolAccessLevelKey = "protocolAccessLevel_19D02A27-A07F-4984-934F-785476927A26";
        private const string ProtocolIdKey = "ProtocolId_12589E7F-CC7F-4e95-A0FB-E7086E014900";

        #endregion

        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                breadCrumb.Add(
                    "Continuing Review: Study Type Selection",
                    Settings.GetKeyValue("SubModuleNavigation.Humans.ContinuingReviewSelectionPageURL", ""),
                    Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));

                pageCache = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();

                annunciator.Message = string.Empty;

                if (! IsPostBack)
                {
                    Hashtable incomingPageHash = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                    if (incomingPageHash != null)
                    {
                        userAccessLevel = Convert.ToInt32(incomingPageHash[Keys.ProtocolAccessKey]);
                        pageCache[ProtocolAccessLevelKey] = userAccessLevel;

                        protocolId = Convert.ToInt32(incomingPageHash[Keys.ProtocolIdKey]);
                        pageCache[ProtocolIdKey] = protocolId;

                        protocol = new Protocol(cachePolicy);
                        protocol.Load(DataAccess.ConnectionString, protocolId);
                        protocol.Cache();

                        processType = (string) (incomingPageHash[Keys.NewProcessTypeKey]);
                        pageCache[ProcessTypeKey] = processType;

                        pageCachePolicy.Cache(PageCacheKey, pageCache);
                        pageCachePolicy.UnCache(Keys.IncomingDataKey);
                    }
                    else
                    {
                        userAccessLevel = (int) pageCache[ProtocolAccessLevelKey];
                        protocolId = (int) pageCache[ProtocolIdKey];
                        questionnaireAnswer = new QuestionnaireAnswer(cachePolicy);
                        questionnaireAnswer = (QuestionnaireAnswer) cachePolicy.GetCachedObject(questionnaireAnswer.CacheKey());
                        processType = (string) (pageCache[ProcessTypeKey]);
                    }
                }
                else
                {
                    userAccessLevel = (int) pageCache[ProtocolAccessLevelKey];
                    protocolId = (int) pageCache[ProtocolIdKey];
                    processType = (string) (pageCache[ProcessTypeKey]);
                    questionnaireAnswer = new QuestionnaireAnswer(cachePolicy);
                    questionnaireAnswer = (QuestionnaireAnswer) cachePolicy.GetCachedObject(questionnaireAnswer.CacheKey());
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
            finally
            {
                protocolDetailHeader.ProtocolID = protocolId;
                //Set the humansubmodule Navigation links
                humansSubModNavigation.Protocol = Protocol;
            }
        }

        private void OnContinueClick(object sender, ImageClickEventArgs e)
        {
            crStudyType = CRTypeList.SelectedValue;

            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
            outgoingData.Add(Keys.ProtocolIdKey, protocolId);
            outgoingData.Add(Keys.NewProcessTypeKey, processType);
            outgoingData.Add(Keys.ContinuingReviewStudyTypeKey, crStudyType);
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

            Page.Response.Redirect(
                Settings.GetKeyValue("SubModuleNavigation.Humans.NewProcessPageURL", ""));
        }

        private void OnCancel(object sender, ImageClickEventArgs e)
        {
            Hashtable outgoingData = new Hashtable();
            outgoingData.Add(Keys.ProtocolIdKey, protocolId);
            outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
            pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

            Response.Redirect(Settings.GetKeyValue("SubModuleNavigation.Humans.ProtocolDetailsURL", ""));
        }

        #region Control Events

        /// <summary>
        /// Resets the subnavigation selected link before the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                humansSubModNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }


        /// <summary>
        /// Resets the subnavigation selected link before the header or the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                humansSubModNavigation.Reset();
                humansSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }


        /// <summary>
        /// Constructs and caches a hashtable of data for use by the page to which nagivation leads
        /// </summary>
        private void OnHumansSubModNavigate()
        {
            try
            {
                Hashtable outgoingData = new Hashtable();
                outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
                outgoingData.Add(Keys.ProtocolIdKey, protocolId);
                outgoingData.Add(Keys.NewProcessTypeKey, processType);
                pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Gets the protocol for which staffing is being reviewed or modified.  If it's not already
        /// in the cache, it loads it up based on the protocolId passed to the page, and caches the object
        /// </summary>
        private Protocol Protocol
        {
            get
            {
                string cacheKey = Protocol.ProtocolKey;
                protocol = cachePolicy.GetCachedObject(cacheKey) as Protocol;

                if ((protocol == null) || (protocolId != protocol.Id))
                {
                    protocol = new Protocol(cachePolicy);
                    protocol.Load(DataAccess.GetConnectionString(), protocolId);
                    cachePolicy.Cache(cacheKey, protocol);
                }
                return protocol;
            }
        }

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = AnnunciatorTitle;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.cancel.Click += new ImageClickEventHandler(OnCancel);
            this.continueCR.Click += new ImageClickEventHandler(OnContinueClick);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion
    }
}